package com.sfms.enter_client;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.common.util.concurrent.ListenableFuture;
import android.Manifest;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class VideoActivity extends AppCompatActivity {
    private PreviewView previewView;
    private Handler handler = new Handler();
    private OkHttpClient client = new OkHttpClient();
    private Runnable httpRequestRunnable;
    private TextView statusText; // 添加 TextView 引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);

        // 初始化状态文本
        statusText = findViewById(R.id.statusText);

        // 获取传递的 IP 地址
        Intent intent = getIntent();
        String ipAddress = intent.getStringExtra("IP_ADDRESS");

        // 初始化摄像头预览
        previewView = findViewById(R.id.videoArea);

        // 检查并请求摄像头权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            startCamera();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }

        // 初始化定时器
        httpRequestRunnable = new Runnable() {
            @Override
            public void run() {
                String url = "http://" + ipAddress + ":8000/entry-recognize/"; // 使用传递的 IP 地址
                sendHttpRequest(url); // 替换URL
                handler.postDelayed(this, 2000); // 每 2 秒执行一次
            }
        };
        handler.post(httpRequestRunnable);
    }

    // 修改 sendHttpRequest 方法
    private void sendHttpRequest(String url) {
        // 从 PreviewView 中捕获当前帧
        Bitmap bitmap = previewView.getBitmap();
        if (bitmap == null) {
            return;
        }

        // 将 Bitmap 保存为临时文件
        File file = new File(getCacheDir(), "temp_image.jpg");
        try (FileOutputStream out = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 创建请求体，添加必要的参数
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(file, MediaType.parse("image/jpeg")))
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        // 发送请求
        new Thread(() -> {
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        statusText.setText("检测成功");
                        handler.postDelayed(() -> statusText.setText(""), 5000);
                    });
                } else {
                    // 处理服务器错误
                    String errorBody = response.body().string();
                    JSONObject errorJson = new JSONObject(errorBody);
                    String errorMessage = errorJson.optString("message", "服务器错误");
                    if (errorMessage.contains("无法识别车牌，请调整位置")) {
                        runOnUiThread(() -> {
                            statusText.setText("无法识别车牌，请调整位置");
                            handler.postDelayed(() -> statusText.setText(""), 5000);
                        });
                    } else if (errorMessage.contains("该车牌号已存在")) {
                        runOnUiThread(() -> {
                            statusText.setText("该车牌号已存在！");
                            handler.postDelayed(() -> statusText.setText(""), 5000);
                        });
                    } else {
                        // 通用错误处理
                        runOnUiThread(() -> {
                            statusText.setText("服务器错误: " + errorMessage);
                            handler.postDelayed(() -> statusText.setText(""), 5000);
                        });
                    }
                }
            } catch (JSONException e) {
                // JSON解析错误
                runOnUiThread(() -> {
                    statusText.setText("解析服务器响应失败");
                    handler.postDelayed(() -> statusText.setText(""), 5000);
                });
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    statusText.setText("网络请求失败: " + e.getMessage());
                    handler.postDelayed(() -> statusText.setText(""), 5000);
                });
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止定时器
        handler.removeCallbacks(httpRequestRunnable);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startCamera();
            } else {
                Toast.makeText(this, "摄像头权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();

                // 设置预览
                Preview preview = new Preview.Builder().build();
                preview.setSurfaceProvider(previewView.getSurfaceProvider());

                // 选择后置摄像头
                CameraSelector cameraSelector = new CameraSelector.Builder()
                        .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                        .build();

                // 绑定生命周期
                cameraProvider.bindToLifecycle(this, cameraSelector, preview);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));
    }
}
